import cv2
import cv2.dnn
import numpy as np
'''
本类对图片进行切割然后进行人脸检测
'''

scale_factor=1.0
input_image_width = 300;
input_image_hight = 300
mean_values = [104., 177.0, 123.0]
confidence_threshold = 0.5

def detect(faceDetectorCvSsD,img,face_list):
    #print("detect ",img.shape)
    ok = faceDetectorCvSsD.ok
    if ok is False:
        return 0

    #scalefactor:图像各通道数值的缩放比例 各通道分别减去20，30，40
    blob = cv2.dnn.blobFromImage(img,scalefactor=scale_factor,size=(input_image_width,input_image_hight),mean=mean_values)
    #print("network is ",ssdDetector.netWork)
    #netWork = faceDetectorCvSsD.netWork
    faceDetectorCvSsD.getNetWork().setInput(blob,"data")
    detection = faceDetectorCvSsD.getNetWork().forward("detection_out")
    #print("detection is ",detection.shape)
    #np.
    #detection_matrix = cv2.CreateMat(detection.size[2],detection.size[3],cv2.CV_32FC3,detection.ptr)
    #np.a
    #识别
    n = 0
    # for i in range(detection_matrix.rows):
    #     confidence = detection_matrix[i][2]
    #     if confidence < confidence_threshold:
    #         continue
    #     x_left_bottom = detection_matrix[i][3]*img.shape[0]
    #     y_left_bottom = detection_matrix[i][4]*img.shape[1]
    #     x_right_top = detection_matrix[i][5]*img.shape[0]
    #     y_right_top = detection_matrix[i][6]*img.shape[1]
    #     face_list.append((x_left_bottom,y_left_bottom,(x_right_top - x_left_bottom), (y_right_top - y_left_bottom)))
    #     n += 1
    #image_id,label,con,m_min,y_min,x_max,y_max
    for detection in detection.reshape(-1, 7):
        #print('detection is ',detection)
        confidence = float(detection[2])
        if confidence > confidence_threshold:
            x_left_bottom = int(detection[3] * img.shape[1])
            y_left_bottom = int(detection[4] * img.shape[0])
            x_right_top = int(detection[5] * img.shape[1])
            y_right_top = int(detection[6] * img.shape[0])
            face_list.append([x_left_bottom, y_left_bottom, (x_right_top - x_left_bottom), (y_right_top - y_left_bottom)])
            n += 1
            #cv.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0))
            #conf = "{:.4f}".format(confidence)
            #font = cv.FONT_HERSHEY_COMPLEX_SMALL
            #cv.putText(img, conf, (xmin, ymin - 5), font, 1, (0, 0, 255))
    return n

